之前的範例,我們都是直接在 vuex 的 state 中把資料設計好,
然後練習 vuex 的流程與操作。
在專案中,資料的部分可能是向後端 server 取得,
接下來我們會使用 ajax 介接 API 來取得資料。
在過去 Vue 會推薦使用 vue-resource 這個套件來協助我們調用 ajax
那麼,在 Vue 框架中還有什麼合適的 ajax 套件推薦呢?
這點 Vue 作者 Evan You 在這篇部落格有說明:Retiring vue-resource
也就是說在 Vue 中使用 ajax 的套件沒有限定,也不需要特別包裝,更不會發生衝突之類的情形。
任何你用得習慣的套件都可以繼續在 Vue 裡面使用囉。
那麼我們知道 ajax 怎麼使用後,應該想問,怎麼樣在元件觸發呢?
比如:
因此,我們需要知道元件的生命週期。

所有紅色匡的部分都是 Vue 包裝好在每個環節中的 Hook
開發者可以根據需求,來使用,
比如:我們以前會使用 document.ready 或 $(document).ready() 這些 Hook
在觸發 ready 後執行初始化與 ajax 向後端 server 溝通。
對應到 Vue 生命週期,
我們可以在 page component 的 created Hook 發出 ajax 請求,
因為此時,data 已經建立了, success 的資料,你可能會塞在 data 與 UI 做雙向綁定。
data() {
  return {
    // 3. data 與 UI 雙向綁定
    datalist: []
  }
},
created() {
  // 1. 元件 created 時候 call API
  fetch('https://www.aws.myserver/get/userinfo', { method: 'GET'})
  .then((response) {
    // 2. success 資料儲存在 data
    this.datalist = response.json();
  })
  .then(error => {
    console.log(error);
  });
},
還記得 vuex 流程中誰負責處理非同步事件嗎? action !
created () {
  // 1. 呼叫 api action
  this.$store.dispatch('actionAJAXexample');
},
computed: mapGetters({
  // 6. 等待通知.. 調用 getter function 取得 state
  datalist: 'getDatalist',
}),
const state = {
  // 5. state 改變,通知 UI 更新
  datalist: [],
}
const getter = {
  // 7. 取得 state
  getDataList = state => state.datalist
}
const actions = {
  actionAJAXexample ({ commit }) {
    // 2. action 發出 ajax
    fetch('https://www.aws.myserver/get/userinfo', { method: 'GET'})
    .then((response) {
	  // 3. success 後把資料丟給 mutation
      commit(types.MY_API_SUCCESS, response.json());
    })
    .then(error => {
      console.log(error);
    });
  }
}
const mutations = {
  [types.MY_API_SUCCESS] (state, data) {
    // 4. 收到資料改變 state
    state.datalist = data;
  },
}
此時 HTML 已經生成,如果要操控 DOM 如 JQuery 可以在這的時間點觸發。
這個我們比較常用在 component 裡面,比如:父層資料更新的時候會觸發這個 Hook
到這邊介紹常用的 3 個 Hook
剩下的 Hook 目前還沒用到,想瞭解更多的朋友再到官網去研究囉。
實作小範例入門 Vue & Vuex 2.0 - github 完整範例
使用 git checkout 切換每天範例。